package edu.sctu.zhu.controller;

import com.google.gson.Gson;
import edu.sctu.zhu.bean.Goods;
import edu.sctu.zhu.bean.Image;
import edu.sctu.zhu.dao.GoodsDao;
import edu.sctu.zhu.dao.ImageDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhu on 2015/10/31.
 */
@RestController
public class ZhangController {
    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private ImageDao imageDao;

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index() {
        ModelAndView model = new ModelAndView();
        model.setViewName("/zhang/index");
        return model;
    }

    @RequestMapping(value = "/goods/search",method = RequestMethod.POST)
    public String goodsSearch(String goodsname){
        List<Goods> goodses = goodsDao.findSerchName("%"+goodsname+"%");
        List<GoodsDetail> detailList = new ArrayList<>();
        if (goodses.size() != 0){
            for (int i = 0;i<goodses.size();i++){
                GoodsDetail goodsDetail = new GoodsDetail();
                Long id = goodses.get(i).getId();
                goodsDetail.goodsname = goodses.get(i).getName();
                goodsDetail.price = goodses.get(i).getPrice();
                List<Image> imageList = imageDao.findByparentId(id);
                if (imageList.size() != 0){
                    for(int j=0;j<imageList.size();j++) {
                        goodsDetail.image = imageList.get(j).getUrl();
                    }
                }
                detailList.add(goodsDetail);
            }
        }
        System.out.println("****************************************************");
        Gson gson = new Gson();
        String json = gson.toJson(detailList);
        return json;
    }

    public class GoodsDetail{
        public String goodsname;
        public Long price;
        public String image;
    }

    /**
     * 已上架商品。
     */
    @RequestMapping(value = "/goods/shelved")
    public void goodsShelved(){

    }
}
